<?php

namespace app\admin\controller\mall;

use app\admin\controller\system\Log;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\lib\Toutiao;
use app\common\model\MallGoods;
use app\common\model\MallManager;
use app\common\model\MallOrder;
use app\common\model\MallPaylog;
use app\common\model\MallSpecsValue;
use app\common\model\MallUser;
use app\common\model\MallUserCertification;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="订单管理")
 */
class Order extends AdminController
{
    use Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model =(new MallOrder());
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $status =$this->request->param('status',-1,'intval');
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            if($status > '-1'){
                $where[] =[['status','=',$status]];
            }

            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $alltotal =0;
            $costtotal =0;
            foreach ($list as $k=>$v){
                $list[$k]['orderno'] =' '.$v['orderno'].' ';
                $alltotal +=$v['payprice'];
                $list[$k]['specs_value_ids'] = $this->getGetSpecsValueIdsAttr($v['specs_value_ids']);
                $costtotal+=$v['cost_price']*$v['goods_num'];
                $users= (new MallUser())->where([['id','=',$v['hxuser_id']]])->find();
                $list[$k]['hxuser'] =!empty($users) ? $users['nickName']:'';
                if($v['hx_time']>0){
                    $list[$k]['hx_time'] =date('Y-m-d H:i:s',$v['hx_time']);
                }else{
                    $list[$k]['hx_time'] ='--';
                }
                if($v['canceltime']>0){
                    $list[$k]['canceltime'] =date('Y-m-d H:i:s',$v['canceltime']);
                }else{
                    $list[$k]['canceltime'] ='--';
                }
                if($v['refund_time']>0){
                    $list[$k]['refund_time'] =date('Y-m-d H:i:s',$v['refund_time']);
                }else{
                    $list[$k]['refund_time'] ='--';
                }
                if($v['pay_time']>0){
                    $list[$k]['pay_time'] =date('Y-m-d H:i:s',$v['pay_time']);
                }else{
                    $list[$k]['pay_time'] ='--';
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
                'alltotal'=>round($alltotal,2),
                'lirun' =>round($alltotal-$costtotal,2)
            ];
            return json($data);
        }
        $managerLists =(new MallManager())->field('id,title')->select()->toArray();
        $managerList = array_column($managerLists,'title','id');
        $this->assign([
            'status'=>$status,
            'managerlist' =>json_encode($managerList),
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="查看详情")
     */
    public function info($id){
        $rowinfo = $this->model->find($id);
        empty($rowinfo) && $this->error('数据不存在');

        $userinfo =(new MallUser())->where([['openid','=',$rowinfo['openid']]])->find();
        $manager =(new MallManager())->where([['id','=',$rowinfo['manager_id']]])->find();

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            if($rowinfo['status'] >=1){
                $this->error('操作异常，请刷新后重试');
            }
            try {
                $post['status'] =1;
                $save = $rowinfo->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }


        $rowinfo['umobile'] =!empty($userinfo) ? $userinfo['mobile']:'';
        $rowinfo['manager'] =!empty($manager)? $manager['title']:'';
        switch ($rowinfo['status']){
            case 0:
                $rowinfo['statusname'] ='待付款';
                break;
            case 1:
                $rowinfo['statusname'] ='待核销';
                break;
            case 2:
                $rowinfo['statusname'] ='已核销';
                break;
            case 3:
                $rowinfo['statusname'] ='已退款';
                break;
            case 4:
                $rowinfo['statusname'] ='订单取消';
                break;
            default:
                break;
        }
        if($rowinfo['pay_time']>0){
            $rowinfo['pay_time'] =date('Y-m-d H:i:s',$rowinfo['pay_time']);
        }else{
            $rowinfo['pay_time']='--';
        }
        $rowinfo['hxnickName']='--';
        if($rowinfo['hx_time']>0){
            $hxuserinfo =(new MallUser())->where([['id','=',$rowinfo['hxuser_id']]])->find();
            $rowinfo['hxnickName'] =$hxuserinfo['nickName'];
            $rowinfo['hx_time'] =date('Y-m-d H:i:s',$rowinfo['hx_time']);
        }else{
            $rowinfo['hx_time']='--';
        }
        if($rowinfo['specs_value_ids']){
            $rowinfo['option_name'] =$this->getGetSpecsValueIdsAttr($rowinfo['specs_value_ids']);
        }else{
            $rowinfo['option_name']='';
        }


        $this->assign('row', $rowinfo);
        return $this->fetch();
    }

    protected function getGetSpecsValueIdsAttr($value){

        if(empty($value)){
            return '默认';
        }
        $ids = explode("-",$value);
        $res= (new MallSpecsValue())->where('id','in',$ids)
            ->select()->toArray();
        $options= '';
        foreach ($res as $k=>$v){
            $options.= $v['title'].' ';
        }
        return $options;
    }

    /**
     * @NodeAnotation(title="商家退款")
     */
    public function torefund($id){
        $rowinfo = $this->model->find($id);
        empty($rowinfo) && $this->error('数据不存在');

        if($rowinfo['status'] !=1){
            $this->error('非法请求');
        }
        $paylog =(new MallPaylog())->getBaseByWhereOne([['order_id','=',$id]]);
        if($paylog && $paylog['status']==1){
            $data =[
                'ordersn'=>$paylog['ordersn'],
                'out_refund_no'=>Str::RandomStr(),
                'money'=>$paylog['money'],
                'reason'=>'商家主动退款'
            ];
            $response= Toutiao::getInstance()->refund_order($data);
            if(isset($response['err_no']) && $response['err_no'] ==0){
                (new MallOrder())->where([['id','=',$id]])->save(['status'=>3,'refund_time'=>time()]);
                $this->success('退款成功');
            }else{
                $this->error('退款异常');
            }
        }else{
            $this->error('退款异常');
        }
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        $where=[];
        $status =$this->request->param('status','-1','intval');
        $ids =$this->request->param('id','','trim');
        $where[]=[['id','in',$ids]];
        if($status !='-1'){
            $where[]=[['status','=',$status]];
        }
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], ['openid','goods_id','market_price','tags','goods_logo','isread','add_date','bonus_id','doors','door_id','update_time','delete_time'])) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        foreach ($list as $k=>$v){
            $list[$k]['orderno'] =' '.$v['orderno'].' ';
            $users= (new MallUser())->where([['id','=',$v['hxuser_id']]])->find();
            $list[$k]['hxuser_id'] =!empty($users) ? $users['nickName']:'';
            $list[$k]['pay_time'] =$v['pay_time']>0? date('Y-m-d H:i:s',$v['pay_time']):'';
            $list[$k]['hx_time'] =$v['hx_time']>0? date('Y-m-d H:i:s',$v['hx_time']):'';
            $list[$k]['canceltime'] =$v['canceltime']>0? date('Y-m-d H:i:s',$v['canceltime']):'';
            $list[$k]['refund_time'] =$v['refund_time']>0? date('Y-m-d H:i:s',$v['refund_time']):'';
            if($v['specs_value_ids']){
                $list[$k]['specs_value_ids'] =$this->getGetSpecsValueIdsAttr($v['specs_value_ids']);
            }else{
                $list[$k]['specs_value_ids']='';
            }
            $manager =(new MallManager())->getBaseByWhereOne([['id','=',$v['manager_id']]]);
            $list[$k]['manager_id']=$manager?$manager['title']:'';
            switch ($v['status']){
                case 0:
                    $list[$k]['status'] ='待支付';
                    break;
                case 1:
                    $list[$k]['status'] ='待核销';
                    break;
                case 2:
                    $list[$k]['status'] ='已核销';
                    break;
                case 3:
                    $list[$k]['status'] ='已退款';
                    break;
                case 4:
                    $list[$k]['status'] ='订单取消';
                    break;
                default:
                    break;
            }
            switch ($v['pay_type']){
                case 1:
                    $list[$k]['pay_type'] ='微信支付';
                    break;
                case 2:
                    $list[$k]['pay_type'] ='支付宝支付';
                    break;
                case 3:
                    $list[$k]['pay_type'] ='合众支付';
                    break;
                default:
                    break;
            }
        }

        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }


}